package com.bindatax.event.impl.statistics.dblog.data;

import com.bindatax.core.log.LogOutInterface;
import com.bindatax.core.log.LogOutManager;
import com.bindatax.core.dspool.DataTaskConnManager;
import com.bindatax.core.meta.TaskMeta;
import com.bindatax.event.impl.statistics.dblog.model.RunTimeLog;
import com.bindatax.event.impl.statistics.dblog.model.ZlLog;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;

public class LogDataOperate {//日志数据操作

    private final String runTimeSql;
    private final String getZlSql;
    private final String setZlSql;
    private TaskMeta taskMeta;
    private final static LogOutInterface LOG = LogOutManager.get();

    private final String connKey;

    public LogDataOperate(TaskMeta taskMeta) {
        this.taskMeta = taskMeta;
        runTimeSql = "INSERT INTO " + taskMeta.getLogSchema()
                + ".T_SXYTH_ETL_LOG_RUNTIME (XZQHDM, XZQHMC, SCHEMA, TABLE_NAME, ZL_OLD_TIME, ZL_NEW_TIME , INPUT_NUM, OUTPUT_NUM,UPDATE_NUM" +
                ", REJECT_NUM ,EXE_STATUS_CODE, EXE_STATUS_DESC, START_TIME, END_TIME, SQL_MODEL_ID, EXE_FAIL_SUMMARY, EXE_FAIL_DATAIL,GROUP_BY,REMARKS)" +
                " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";

        getZlSql = "SELECT ZLSJ FROM " + taskMeta.getLogSchema() + ".T_SXYTH_ETL_ZL_INFO" + " WHERE  ID = ?";
        setZlSql = "MERGE INTO " + taskMeta.getLogSchema() +
                ".T_SXYTH_ETL_ZL_INFO T1 USING ( SELECT ? AS ID FROM DUAL ) T2 ON ( T1.ID = T2.ID ) WHEN MATCHED THEN" +
                "   UPDATE SET T1.XZQHDM = ?, T1.XZQHMC = ?, T1.SCHEMA = ?, T1.SQL_GUID = ?, T1.TABLENAME = ?, T1.ZLSJ = ?, T1.JLGXSJ = ?" +
                "  WHEN NOT MATCHED THEN  INSERT( ID,XZQHDM,XZQHMC,SCHEMA,SQL_GUID,TABLENAME,ZLSJ,JLGXSJ )  VALUES( ?,?,?,?,?,?,?,?) ";
        try {
            connKey = DataTaskConnManager.buildConnection(taskMeta.getLogUrl(),
                    taskMeta.getLogUser(),
                    taskMeta.getLogPwd(),
                    taskMeta.getLogDriver(),
                    taskMeta.getLogValidationQuery()
            );
        } catch (Exception e) {
            LOG.error("获取日志数据源连接失败！",e);
            throw new RuntimeException(e);
        }
    }

    public void saveRunTimeLog(RunTimeLog log) {
        Connection logConnect = null;
        PreparedStatement logStatement = null;
        try {
            LOG.info("把程序执行日志记录写到日志表中。[组：" + log.getGroupBy() + " / 行政区划名称：" + log.getXzqhmc() + " / SCHEMA：" + log.getSchema() + " / 表：" + log.getTableName());
            logConnect = DataTaskConnManager.getConnection(connKey);
            logConnect.setAutoCommit(false);
            logStatement = logConnect.prepareStatement(runTimeSql);
            logStatement.setObject(1, log.getXzqhdm());
            logStatement.setObject(2, log.getXzqhmc());
            logStatement.setObject(3, log.getSchema());
            logStatement.setObject(4, log.getTableName());
            logStatement.setObject(5, log.getZlOldTime());
            logStatement.setObject(6, log.getZlNewTime());
            logStatement.setObject(7, log.getInput());
            logStatement.setObject(8, log.getOutput());
            logStatement.setObject(9, log.getUpdate());
            logStatement.setObject(10, log.getReject());
            logStatement.setObject(11, log.getExeStatusCode());
            logStatement.setObject(12, log.getExeStatusDesc());
            logStatement.setObject(13, log.getStartTime());
            logStatement.setObject(14, log.getEndTime());
            logStatement.setObject(15, log.getSqlGuid());
            logStatement.setObject(16, log.getExeFailSummary());
            logStatement.setObject(17, log.getExeFailDatail());
            logStatement.setObject(18, log.getGroupBy());
            logStatement.setObject(19, log.getRemarks());
            logStatement.execute();
            logConnect.commit();
        } catch (Exception e) {
            LOG.error("写入运行日志到数据库失败！",e);
        } finally {
            DataTaskConnManager.close(null, logStatement, logConnect);
        }
    }

    public void saveZlTime(ZlLog zlLog) {
        Connection logConnect = null;
        PreparedStatement logStatement = null;
        try {
            logConnect = DataTaskConnManager.getConnection(connKey);
            logConnect.setAutoCommit(false);
            logStatement = logConnect.prepareStatement(setZlSql);
            logStatement.setObject(1, zlLog.getId());
            logStatement.setObject(2, zlLog.getXzqhdm());
            logStatement.setObject(3, zlLog.getXzqhmc());
            logStatement.setObject(4, zlLog.getSchema());
            logStatement.setObject(5, zlLog.getSqlGuid());
            logStatement.setObject(6, zlLog.getTableName());
            logStatement.setObject(7, zlLog.getZlsj());
            logStatement.setObject(8, new Timestamp(System.currentTimeMillis()));
            logStatement.setObject(9, zlLog.getId());
            logStatement.setObject(10, zlLog.getXzqhdm());
            logStatement.setObject(11, zlLog.getXzqhmc());
            logStatement.setObject(12, zlLog.getSchema());
            logStatement.setObject(13, zlLog.getSqlGuid());
            logStatement.setObject(14, zlLog.getTableName());
            logStatement.setObject(15, zlLog.getZlsj());
            logStatement.setObject(16, new Timestamp(System.currentTimeMillis()));
            logStatement.execute();
            logConnect.commit();
        } catch (Exception e) {
            LOG.error("写入增量数据到数据库失败！",e);
        } finally {
            DataTaskConnManager.close(null, logStatement, logConnect);
        }
    }

    public Timestamp queryZlTime(String id) {
        Timestamp zlsj = null;
        Connection logConnect = null;
        PreparedStatement logStatement = null;
        ResultSet logResultSet = null;
        try {
            logConnect = DataTaskConnManager.getConnection(connKey);
            logStatement = logConnect.prepareStatement(getZlSql);
            logStatement.setObject(1, id);
            logResultSet = logStatement.executeQuery();
            while (logResultSet.next()) {
                zlsj = logResultSet.getTimestamp("ZLSJ");
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DataTaskConnManager.close(logResultSet, logStatement, logConnect);
        }
        return zlsj;
    }
}
